/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2024-12-24 00:00:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2024-12-24 00:00:00
 * @FilePath: \project\work-tool\experi-api\routes\dynamic-routes.js
 * @Description: 动态创建接口的路由模块
 */
var express = require('express');
var router = express.Router();

// 存储动态创建的路由信息
const dynamicRoutes = [];

/**
 * 创建新的动态接口
 * @param {String} path - 接口路径
 * @param {String} method - 请求方法 (GET 或 POST)
 * @param {Object} response - 返回的数据结构
 */
function createDynamicRoute(path, method, response) {
    // 检查是否已存在相同路径和方法的路由
    const existingRoute = dynamicRoutes.find(
        route => route.path === path && route.method.toLowerCase() === method.toLowerCase()
    );
    
    if (existingRoute) {
        return { success: false, message: '该接口已存在' };
    }
    
    // 生成路由ID
    const routeId = Date.now().toString();
    
    // 注册新的路由
    if (method.toLowerCase() === 'get') {
        router.get(path, (req, res) => {
            res.json(response || {
                code: 200,
                message: `动态创建的GET接口: ${path}`,
                data: req.query
            });
        });
    } else if (method.toLowerCase() === 'post') {
        router.post(path, (req, res) => {
            res.json(response || {
                code: 200,
                message: `动态创建的POST接口: ${path}`,
                data: req.body
            });
        });
    } else {
        return { success: false, message: '只支持GET和POST方法' };
    }
    
    // 保存路由信息
    dynamicRoutes.push({
        id: routeId,
        path: path,
        method: method.toUpperCase(),
        createdAt: new Date(),
        response: response
    });
    
    return { success: true, routeId, path, method: method.toUpperCase() };
}

/**
 * 获取所有动态创建的路由列表
 */
function getDynamicRoutes() {
    return dynamicRoutes;
}

/**
 * 获取指定路由的使用方法
 */
function getRouteUsage(routeId) {
    const route = dynamicRoutes.find(r => r.id === routeId);
    if (!route) {
        return null;
    }
    
    const baseUrl = 'http://localhost:3008';
    const fullPath = baseUrl + route.path;
    
    let usage = {
        id: route.id,
        path: route.path,
        method: route.method,
        fullUrl: fullPath,
        createdAt: route.createdAt,
        description: `这是一个动态创建的${route.method}接口`,
        examples: []
    };
    
    // 添加使用示例
    if (route.method === 'GET') {
        usage.examples.push({
            title: '浏览器访问',
            example: fullPath + '?param1=value1&param2=value2'
        });
        usage.examples.push({
            title: 'cURL命令',
            example: `curl "${fullPath}?param1=value1&param2=value2"`
        });
        usage.examples.push({
            title: 'Fetch API',
            example: `fetch('${fullPath}?param1=value1&param2=value2')\n  .then(response => response.json())\n  .then(data => console.log(data))`
        });
    } else if (route.method === 'POST') {
        usage.examples.push({
            title: 'cURL命令',
            example: `curl -X POST \"${fullPath}\" \\n  -H \"Content-Type: application/json\" \\n  -d '{\"param1\": \"value1\", \"param2\": \"value2\"}'`
        });
        usage.examples.push({
            title: 'Fetch API',
            example: `fetch('${fullPath}', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({ param1: 'value1', param2: 'value2' })\n})\n  .then(response => response.json())\n  .then(data => console.log(data))`
        });
    }
    
    return usage;
}

// API接口: 创建新的动态接口
router.post('/dynamic/create', (req, res) => {
    const { path, method, response } = req.body;
    
    // 验证参数
    if (!path || !method) {
        return res.status(400).json({
            code: 400,
            message: '缺少必要参数: path和method',
            data: null
        });
    }
    
    if (method.toLowerCase() !== 'get' && method.toLowerCase() !== 'post') {
        return res.status(400).json({
            code: 400,
            message: '只支持GET和POST方法',
            data: null
        });
    }
    
    // 确保path以/开头
    const formattedPath = path.startsWith('/') ? path : '/' + path;
    
    // 创建动态路由
    const result = createDynamicRoute(formattedPath, method, response);
    
    if (result.success) {
        res.json({
            code: 200,
            message: '动态接口创建成功',
            data: {
                routeId: result.routeId,
                path: result.path,
                method: result.method,
                fullUrl: 'http://localhost:3008' + result.path,
                usageUrl: 'http://localhost:3008/dynamic/usage/' + result.routeId
            }
        });
    } else {
        res.status(400).json({
            code: 400,
            message: result.message,
            data: null
        });
    }
});

// API接口: 获取所有动态创建的接口列表
router.get('/dynamic/list', (req, res) => {
    const routes = getDynamicRoutes();
    res.json({
        code: 200,
        message: '获取动态接口列表成功',
        data: routes
    });
});

// API接口: 获取指定接口的使用方法
router.get('/dynamic/usage/:routeId', (req, res) => {
    const { routeId } = req.params;
    const usage = getRouteUsage(routeId);
    
    if (usage) {
        res.json({
            code: 200,
            message: '获取接口使用方法成功',
            data: usage
        });
    } else {
        res.status(404).json({
            code: 404,
            message: '未找到指定的接口',
            data: null
        });
    }
});

// API接口: 删除指定的动态接口
router.delete('/dynamic/delete/:routeId', (req, res) => {
    const { routeId } = req.params;
    const routeIndex = dynamicRoutes.findIndex(r => r.id === routeId);
    
    if (routeIndex !== -1) {
        dynamicRoutes.splice(routeIndex, 1);
        // 注意：这里只是从内存中移除了路由信息，但不会实际从Express路由表中移除路由
        // 在实际生产环境中，可能需要更复杂的实现来动态移除路由
        res.json({
            code: 200,
            message: '动态接口已删除（注意：仅从内存记录中移除，应用重启后完全生效）',
            data: null
        });
    } else {
        res.status(404).json({
            code: 404,
            message: '未找到指定的接口',
            data: null
        });
    }
});

module.exports = router;